/**
 * Copyright (C) 2009 Ignasi Fosch Alonso
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 
 * details.
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * You can reach me by mail at natx@y10k.ws
 * You can reach him by paper mail at:
 * C. LLEIDA, 41-43, 3r 1a
 * El Prat de Llobregat 08820
 * Barcelona, SPAIN
 */
package ws.y10k.goloim.interfaces.swt;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.TableItem;

import ws.y10k.goloim.model.Box;
import ws.y10k.goloim.model.BoxDoesNotExistException;
import ws.y10k.goloim.model.Pallet;
import ws.y10k.goloim.model.PalletDoesNotExistException;
import ws.y10k.goloim.model.Product;
import ws.y10k.goloim.model.ProductAlreadyExistsException;
import ws.y10k.goloim.model.ProductDoesNotExistException;

/**
 * @author natx
 *
 */
public class SaveProductSelectionListener implements SelectionListener {
	
	private AddProductWindow parent;
	
	public SaveProductSelectionListener(AddProductWindow parent) {
		this.parent = parent;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
	 */
	@Override
	public void widgetDefaultSelected(SelectionEvent arg0) { }

	/* (non-Javadoc)
	 * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
	 */
	@Override
	public void widgetSelected(SelectionEvent arg0) {
		// TODO i18n
		if ( parent.txtReference.getText().length() > 0 ) {
			String reference = parent.txtReference.getText();
			String description = parent.txtDescription.getText();
			String details = parent.txtDetails.getText();
			String supplier = parent.txtSupplier.getText();
			double unitNetWeight;
			try {
				unitNetWeight = Double.parseDouble(parent.txtUnitNetWeight.getText());
			} catch (NumberFormatException e) {
				MessageDialog.openError(parent.getShell(), "Format error in unit net weight field", "Unit net weight field must be a number.");
				return;
			}
			double unitGrossWeight;
			try {
				unitGrossWeight = Double.parseDouble(parent.txtUnitGrossWeight.getText());
			} catch (NumberFormatException e) {
				MessageDialog.openError(parent.getShell(), "Format error in unit gross weight field", "Unit gross weight field must be a number.");
				return;
			}
			int unitsPerBox;
			try {
				unitsPerBox = Integer.parseInt(parent.txtUnitsPerBox.getText());
			} catch (NumberFormatException e) {
				MessageDialog.openError(parent.getShell(), "Format error in units per box field", "Units per box field must be a number.");
				return;
			}
			String[] boxData1 = parent.cmbBox.getItem(parent.cmbBox.getSelectionIndex()).split(" ");
			String[] boxData2 = boxData1[0].split("x");
			Box box;
			try {
				box = GoLoIm.boxes.getBox(Double.parseDouble(boxData2[0]), Double.parseDouble(boxData2[1]), Double.parseDouble(boxData2[2]), Double.parseDouble(boxData1[1]));
			} catch (BoxDoesNotExistException e2) {
				MessageDialog.openError(parent.getShell(), "No box selected", "You have to choose a box.");
				return;
			}
			int boxesPerLayer;
			try {
				boxesPerLayer = Integer.parseInt(parent.txtBoxesPerLayer.getText());
			} catch (NumberFormatException e) {
				MessageDialog.openError(parent.getShell(), "Format error in boxes per layer field", "Boxes per layer field must be a number.");
				return;
			}
			int layersPerPallet;
			try {
				layersPerPallet = Integer.parseInt(parent.txtLayersPerPallet.getText());
			} catch (NumberFormatException e) {
				MessageDialog.openError(parent.getShell(), "Format error in layers per pallet field", "Layers per pallet field must be a number.");
				return;
			}
			Pallet pallet;
			try {
				pallet = GoLoIm.pallets.getPallet(parent.cmbPallet.getItem(parent.cmbPallet.getSelectionIndex()));
			} catch (PalletDoesNotExistException e1) {
				MessageDialog.openError(parent.getShell(), "No pallet selected", "You have to choose a pallet.");
				return;
			}
			boolean stackable = false;
			if ( parent.btnStackable.getSelection() ) stackable = true;
			
			try {
				Product product = new Product(reference,description,details,supplier,unitNetWeight,unitGrossWeight,unitsPerBox,box,boxesPerLayer,layersPerPallet,pallet,stackable);

				if ( parent.itmSelected != null ) {
					try {
						Product oldProduct = GoLoIm.products.getProduct(parent.txtReference.getText());
						oldProduct.setReference(reference);
						oldProduct.setDescription(description);
						oldProduct.setDetails(details);
						oldProduct.setSupplier(supplier);
						oldProduct.setUnitNetWeight(unitNetWeight);
						oldProduct.setUnitGrossWeight(unitGrossWeight);
						oldProduct.setUnitsPerBox(unitsPerBox);
						oldProduct.setBox(box);
						oldProduct.setBoxesPerLayer(boxesPerLayer);
						oldProduct.setLayersPerPallet(layersPerPallet);
						oldProduct.setPallet(pallet);
						oldProduct.setStackable(stackable);
						String strStackable = "N";
						if ( stackable ) strStackable = "Y";
						String[] values = {reference,description,details,supplier,((Double) unitNetWeight).toString(),((Integer) unitsPerBox).toString(),box.getWidth() + "x" + box.getHeight() + "x" + box.getDepth() + " " + box.getWeight(),((Integer) boxesPerLayer).toString(),((Integer) layersPerPallet).toString(),pallet.getCode(),strStackable};
						parent.itmSelected.setText(values);
						parent.itmSelected = null;
						parent.tblProducts.deselectAll();
					} catch (ProductDoesNotExistException e) { }
				} else {
					GoLoIm.products.add(product);
					TableItem itmProduct = new TableItem(parent.tblProducts, SWT.NONE);
					itmProduct.setText(0,product.getReference());
					itmProduct.setText(1,product.getDescription());
					itmProduct.setText(2,product.getDetails());
					itmProduct.setText(3,product.getSupplier());
					itmProduct.setText(4,((Double) product.getUnitNetWeight()).toString());
					itmProduct.setText(5,((Double) product.getUnitGrossWeight()).toString());
					itmProduct.setText(6,((Integer) product.getUnitsPerBox()).toString());
					itmProduct.setText(7,product.getBox().getWidth() + "x" + product.getBox().getHeight() + "x" + product.getBox().getDepth() + " " + product.getBox().getWeight());
					itmProduct.setText(8,((Integer) product.getBoxesPerLayer()).toString());
					itmProduct.setText(9,((Integer) product.getLayersPerPallet()).toString());
					itmProduct.setText(10,product.getPallet().getCode());
					String strStackable = "N";
					if ( product.isStackable() ) strStackable = "Y";
					itmProduct.setText(11,strStackable);
				}
				parent.txtReference.setText("");
				parent.txtDescription.setText("");
				parent.txtDetails.setText("");
				parent.txtSupplier.setText("");
				parent.txtUnitNetWeight.setText("");
				parent.txtUnitGrossWeight.setText("");
				parent.txtUnitsPerBox.setText("");
				parent.cmbBox.deselectAll();
				parent.txtBoxesPerLayer.setText("");
				parent.txtLayersPerPallet.setText("");
				parent.cmbPallet.deselectAll();
				parent.btnStackable.setSelection(false);
				parent.txtReference.setFocus();
			} catch (ProductAlreadyExistsException e) {
				MessageDialog.openError(parent.getShell(), "Product already exists", "A product like that already exists.");
			}
		} else {
			MessageDialog.openError(parent.getShell(), "Not enough information", "You must specify the product reference.");
		}
	}

}
